﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;

namespace MyEmulators2
{
    internal partial class Conf_EmuBrowser : ContentPanel
    {
        public Conf_EmuBrowser()
        {
            InitializeComponent();
            addEventHandlers();
            setupToolTip();
            //this.HandleDestroyed += new EventHandler(Conf_EmuBrowser_HandleDestroyed);
        }

        void Conf_EmuBrowser_HandleDestroyed(object sender, EventArgs e)
        {
            close();
            if (emuThumbs != null)
                emuThumbs.Dispose();
        }

        List<ListViewItem> dbEmus = null;
        ListViewItem selectedListItem = null;
        Emulator selectedEmulator = null;
        bool saveSelectedEmulator = false;
        bool saveThumbs = false;
        EmulatorProfile selectedProfile = null;
        bool saveProfile = false;
        ThumbGroup emuThumbs = null;

        bool updateEmuPositions = false;

        //add changed event handlers to controls
        //to determine whether to update selected Emulator 
        void addEventHandlers()
        {
            emulatorListView.ItemSelectionChanged += new ListViewItemSelectionChangedEventHandler(emulatorListView_ItemSelectionChanged);
            profileComboBox.SelectedIndexChanged += new EventHandler(profileComboBox_SelectedIndexChanged);

            txt_Title.TextChanged += new EventHandler(onItemChanged);
            romDirTextBox.TextChanged += new EventHandler(onItemChanged);
            filterTextBox.TextChanged += new EventHandler(onItemChanged);
            txt_company.TextChanged += new EventHandler(onItemChanged);
            txt_yearmade.TextChanged += new EventHandler(onItemChanged);
            txt_description.TextChanged += new EventHandler(onItemChanged);
            gradeUpDown.ValueChanged += new EventHandler(onItemChanged);

            txt_Manual.TextChanged += new EventHandler(onItemChanged);

            enableGoodCheckBox.CheckedChanged += new EventHandler(onItemChanged);

            pnlLogo.BackgroundImageChanged += new EventHandler(onThumbChanged);
            pnlFanart.BackgroundImageChanged += new EventHandler(onThumbChanged);

            emuPathTextBox.TextChanged += new EventHandler(onProfileChanged);
            emuPathTextBox.TextChanged += new EventHandler(emuPathTextBox_TextChanged);
            workingDirTextBox.TextChanged += new EventHandler(onProfileChanged);
            argumentsTextBox.TextChanged += new EventHandler(onProfileChanged);
            useQuotesCheckBox.CheckedChanged += new EventHandler(onProfileChanged);
            suspendMPCheckBox.CheckedChanged += new EventHandler(onProfileChanged);

            good1ComboBox.TextChanged += new EventHandler(onProfileChanged);
            good2ComboBox.TextChanged += new EventHandler(onProfileChanged);
            good3ComboBox.TextChanged += new EventHandler(onProfileChanged);

            mountImagesCheckBox.CheckedChanged += new EventHandler(onProfileChanged);
            escExitCheckBox.CheckedChanged += new EventHandler(onProfileChanged);
        }

        //Remove event handlers when we are updating the selection.
        //Is there a better way??
        void removeEventHandlers()
        {
            emulatorListView.ItemSelectionChanged -= new ListViewItemSelectionChangedEventHandler(emulatorListView_ItemSelectionChanged);
            profileComboBox.SelectedIndexChanged -= new EventHandler(profileComboBox_SelectedIndexChanged);

            txt_Title.TextChanged -= new EventHandler(onItemChanged);
            romDirTextBox.TextChanged -= new EventHandler(onItemChanged);
            filterTextBox.TextChanged -= new EventHandler(onItemChanged);
            txt_company.TextChanged -= new EventHandler(onItemChanged);
            txt_yearmade.TextChanged -= new EventHandler(onItemChanged);
            txt_description.TextChanged -= new EventHandler(onItemChanged);
            gradeUpDown.ValueChanged -= new EventHandler(onItemChanged);

            txt_Manual.TextChanged -= new EventHandler(onItemChanged);

            enableGoodCheckBox.CheckedChanged -= new EventHandler(onItemChanged);

            pnlLogo.BackgroundImageChanged -= new EventHandler(onThumbChanged);
            pnlFanart.BackgroundImageChanged -= new EventHandler(onThumbChanged);

            emuPathTextBox.TextChanged -= new EventHandler(onProfileChanged);
            emuPathTextBox.TextChanged -= new EventHandler(emuPathTextBox_TextChanged);

            workingDirTextBox.TextChanged -= new EventHandler(onProfileChanged);
            argumentsTextBox.TextChanged -= new EventHandler(onProfileChanged);
            useQuotesCheckBox.CheckedChanged -= new EventHandler(onProfileChanged);
            suspendMPCheckBox.CheckedChanged -= new EventHandler(onProfileChanged);

            good1ComboBox.TextChanged -= new EventHandler(onProfileChanged);
            good2ComboBox.TextChanged -= new EventHandler(onProfileChanged);
            good3ComboBox.TextChanged -= new EventHandler(onProfileChanged);

            mountImagesCheckBox.CheckedChanged -= new EventHandler(onProfileChanged);
            escExitCheckBox.CheckedChanged -= new EventHandler(onProfileChanged);
        }

        //Fired when a new profile is seleced from the profile dropdown.
        //Save any changes to current profile and update panel with new
        //profile details.
        void profileComboBox_SelectedIndexChanged(object sender, EventArgs e)
        {
            updateProfile();

            selectedProfile = profileComboBox.SelectedItem as EmulatorProfile;
            if (selectedProfile == null)
                return;

            removeEventHandlers(); //don't fire changed wvent when we are updating

            emuPathTextBox.Text = selectedProfile.EmulatorPath;
            workingDirTextBox.Text = selectedProfile.WorkingDirectory;
            argumentsTextBox.Text = selectedProfile.Arguments;
            useQuotesCheckBox.Checked = selectedProfile.UseQuotes == true;
            suspendMPCheckBox.Checked = selectedProfile.SuspendMP == true;

            good1ComboBox.Text = selectedProfile.GoodMergePref1;
            good2ComboBox.Text = selectedProfile.GoodMergePref2;
            good3ComboBox.Text = selectedProfile.GoodMergePref3;

            mountImagesCheckBox.Checked = selectedProfile.MountImages;
            escExitCheckBox.Checked = selectedProfile.EscapeToExit;

            addEventHandlers();

            updateButtons();
        }

        private void updateButtons()
        {
            //Default profile selected, don't allow rename or delete.
            if (selectedProfile != null && selectedProfile.ID == -1)
            {
                delProfileButton.Enabled = false;
                renameProfileButton.Enabled = false;
            }
            else
            {
                delProfileButton.Enabled = true;
                renameProfileButton.Enabled = true;
            }

            upButton.Enabled = true;
            downButton.Enabled = true;

            if (selectedListItem != null)
            {
                if (selectedListItem.Index == 0)
                {
                    upButton.Enabled = false; //top of list, don't allow up
                }
                if (selectedListItem.Index == emulatorListView.Items.Count - 1)
                {
                    downButton.Enabled = false; //bottom of list, don't allow down
                }
            }
        }

        private void updateProfile()
        {
            if (!saveProfile || selectedProfile == null)
                return; //no changes have been made or no profile is selected

            selectedProfile.EmulatorPath = emuPathTextBox.Text;
            selectedProfile.WorkingDirectory = workingDirTextBox.Text;
            selectedProfile.Arguments = argumentsTextBox.Text;
            selectedProfile.UseQuotes = useQuotesCheckBox.Checked;
            selectedProfile.SuspendMP = suspendMPCheckBox.Checked;
            selectedProfile.GoodMergePref1 = good1ComboBox.Text;
            selectedProfile.GoodMergePref2 = good2ComboBox.Text;
            selectedProfile.GoodMergePref3 = good3ComboBox.Text;
            selectedProfile.MountImages = mountImagesCheckBox.Checked;
            selectedProfile.EscapeToExit = escExitCheckBox.Checked;

            selectedProfile.Save();

            //if default profile, update listview tag to latest emulator
            //as saving profile does not modify the selected emulator
            if (selectedProfile.ID == -1 && selectedListItem != null)
            {
                Emulator emu = DB.Instance.GetEmulator(selectedEmulator.UID);
                selectedListItem.Tag = emu;
                selectedEmulator = emu;
            }

            saveProfile = false;
        }

        //Fired when the user changes emulator details
        void onItemChanged(object sender, EventArgs e)
        {
            saveSelectedEmulator = true;
        }

        //Fired when the user changes emulator thumbs
        void onThumbChanged(object sender, EventArgs e)
        {
            saveSelectedEmulator = true;
            saveThumbs = true;
        }

        //Fired when the user changes an emulator profile
        void onProfileChanged(object sender, EventArgs e)
        {
            saveProfile = true;
        }

        #region Database ListView

        volatile bool listLoading = false;
        //populate the list view with all emulators
        void initListView()
        {
            if (listLoading)
                return;

            listLoading = true;
            dbEmus = new List<ListViewItem>();
            loadingEmusPanel.Visible = true; //display the loading panel
            emulatorListView.BeginUpdate();
            emulatorListView.Items.Clear();

            //load on seperate thread to ensure responsiveness
            Thread thread = new Thread(new ThreadStart(delegate()
            {
                Emulator[] emus = DB.Instance.GetEmulatorsAndPC();

                for (int x = 0; x < emus.Length; x++)
                {
                    ListViewItem item = new ListViewItem(emus[x].Title);
                    item.Tag = emus[x]; //keep reference to emulator
                    try
                    {
                        //add the emulators to the list view on main thread
                        Invoke(new MethodInvoker(delegate
                        {
                            dbEmus.Add(item);
                            emulatorListView.Items.Add(item);
                        }
                        ));
                    }
                    catch (InvalidOperationException)
                    {
                        //form closed before complete
                        return;
                    }
                }
                try
                {
                    BeginInvoke(new MethodInvoker(delegate
                    {
                        if (emulatorListView.Items.Count > 0)
                            emulatorListView.Items[0].Selected = true;
                        emulatorListView.EndUpdate();
                        loadingEmusPanel.Visible = false;
                        listLoading = false;
                    }
                        ));
                }
                catch { listLoading = false; } //form closed before complete
            }
            ));

            thread.Name = "Emulator browser populator";
            thread.Start();
        }

        //Fired when the user selectes an item in the listview
        void emulatorListView_ItemSelectionChanged(object sender, ListViewItemSelectionChangedEventArgs e)
        {
            //This event is fired twice, once for the item losing selection
            //and once for the item being selected. Ensure we only process
            //one for performance.
            if (!e.IsSelected)
                return;

            updateEmulator();
            updateProfile();

            if (emulatorListView.SelectedItems.Count != 1)
            {
                //multiple items selected, shouldn't occur
                //with current setup but just in case.
                selectedListItem = null;
                selectedEmulator = null;
                selectedProfile = null;
                return;
            }

            selectedListItem = e.Item;
            //update panel with selected emu details
            setEmulatorToPanel(emulatorListView.SelectedItems[0]);
            //update panel enablings
            updatePanels();
        }

        //disables the profile panel when the PC Emulator is selected
        private void updatePanels()
        {
            if (selectedEmulator == null)
                return;

            if (selectedEmulator.UID == -1) //PC Emulator don't allow profile edit
            {
                profGroupBox.Enabled = false;
                romDirTextBox.Enabled = false;
                romDirButton.Enabled = false;
                filterTextBox.Enabled = false;
                enableGoodCheckBox.Enabled = false;
            }
            else
                profGroupBox.Enabled = true;
                romDirTextBox.Enabled = true;
                romDirButton.Enabled = true;
                filterTextBox.Enabled = true;
                enableGoodCheckBox.Enabled = true;
        }

        //Updates the panels with the selected Emulator's details.
        private void setEmulatorToPanel(ListViewItem listViewItem)
        {
            //reset status flags
            saveSelectedEmulator = false;
            saveThumbs = false;
            saveProfile = false;
            //get the selected Emulator
            Emulator dbEmu = listViewItem.Tag as Emulator;
            selectedEmulator = dbEmu;

            if (dbEmu == null)
                return;

            removeEventHandlers();

            txt_Title.Text = dbEmu.Title;
            romDirTextBox.Text = dbEmu.PathToRoms;
            filterTextBox.Text = dbEmu.Filter;
            txt_company.Text = dbEmu.Company;
            txt_yearmade.Text = dbEmu.Yearmade.ToString();
            txt_description.Text = dbEmu.Description;
            gradeUpDown.Value = dbEmu.Grade;
            enableGoodCheckBox.Checked = dbEmu.EnableGoodmerge;

            idLabel.Text = dbEmu.UID.ToString();

            if (emuThumbs != null)
            {
                emuThumbs.Dispose();
            }

            emuThumbs = new ThumbGroup(dbEmu);

            txt_Manual.Text = emuThumbs.ManualPath;

            pnlLogo.ThumbGroup = emuThumbs;
            pnlFanart.ThumbGroup = emuThumbs;

            selectedProfile = null;
            profileComboBox.Items.Clear();
            foreach (EmulatorProfile profile in DB.Instance.GetProfiles(selectedEmulator))
            {
                profileComboBox.Items.Add(profile);
                if (profile.IsDefault)
                {
                    profileComboBox.SelectedItem = profile;
                    selectedProfile = profile;
                }
            }

            addEventHandlers();

            profileComboBox_SelectedIndexChanged(profileComboBox, new EventArgs());
        }

        void clearForm()
        {
            removeEventHandlers();

            saveSelectedEmulator = false;
            saveProfile = false;
            saveThumbs = false;

            txt_Title.Text = "";
            romDirTextBox.Text = "";
            filterTextBox.Text = "";
            txt_company.Text = "";
            txt_yearmade.Text = "";
            txt_description.Text = "";
            gradeUpDown.Value = 0;

            txt_Manual.Text = "";
            idLabel.Text = "";

            enableGoodCheckBox.Checked = false;
            if (platformComboBox.Items.Count > 0)
                platformComboBox.SelectedIndex = 0;
            emuPathTextBox.Text = "";
            argumentsTextBox.Text = "";
            workingDirTextBox.Text = "";
            useQuotesCheckBox.Checked = true;
            suspendMPCheckBox.Checked = false;
            good1ComboBox.Text = "";
            good2ComboBox.Text = "";
            good3ComboBox.Text = "";

            mountImagesCheckBox.Checked = false;
            escExitCheckBox.Checked = false;

            if (emuThumbs != null)
            {
                emuThumbs.Dispose();
                emuThumbs = null;
            }
            pnlLogo.ThumbGroup = null;
            pnlFanart.ThumbGroup = null;

            addEventHandlers();
        }

        private void updateEmulator()
        {
            if (!saveSelectedEmulator || selectedEmulator == null)
                return;

            selectedEmulator.Title = txt_Title.Text;
            if (selectedListItem != null)
            {
                selectedListItem.Text = selectedEmulator.Title;
            }

            selectedEmulator.PathToRoms = romDirTextBox.Text;
            selectedEmulator.Filter = filterTextBox.Text;
            selectedEmulator.Company = txt_company.Text;
            selectedEmulator.Description = txt_description.Text;
            selectedEmulator.Grade = (int)gradeUpDown.Value;

            int year;
            if (!int.TryParse(txt_yearmade.Text, out year))
                year = 0;
            selectedEmulator.Yearmade = year;
            selectedEmulator.EnableGoodmerge = enableGoodCheckBox.Checked;

            selectedEmulator.Save();

            if (emuThumbs != null)
            {
                emuThumbs.ManualPath = txt_Manual.Text;
                emuThumbs.SaveManual();
                if (saveThumbs)
                    emuThumbs.SaveAllThumbs();
            }

            saveSelectedEmulator = false;
        }

        #endregion

        #region Overrides

        public override void update()
        {
            initListView();
            base.update();
        }

        public override void save()
        {
            updateEmulator();
            updateProfile();
            updatePositions();
            base.save();
        }

        public override void close()
        {
            save();

            if (emuThumbs != null)
                emuThumbs.Dispose();

            base.close();
        }

        void updatePositions()
        {
            if (!updateEmuPositions)
                return;

            foreach (ListViewItem item in emulatorListView.Items)
            {
                Emulator emu = item.Tag as Emulator;
                emu.Position = item.Index;
                emu.SavePosition();
            }
            updateEmuPositions = false;
        }

        #endregion

        void Conf_EmuBrowser_Load(object sender, EventArgs e)
        {
        }

        private void addProfileButton_Click(object sender, EventArgs e)
        {
            if (selectedEmulator == null)
                return;

            using (Conf_NewProfile profileDlg = new Conf_NewProfile(selectedEmulator, null))
            {
                if (profileDlg.ShowDialog() != DialogResult.OK || profileDlg.EmulatorProfile == null)
                    return;

                EmulatorProfile profile = profileDlg.EmulatorProfile;
                profile.Save();
                profileComboBox.Items.Add(profile);
                profileComboBox.SelectedItem = profile;
            }
        }

        private void delProfileButton_Click(object sender, EventArgs e)
        {
            if (selectedProfile.ID == -1)
            {
                Logger.LogDebug("Default profile cannot be deleted");
                return;
            }

            EmulatorProfile profile = selectedProfile;
            saveProfile = false;
            selectedProfile = null;
            profile.Delete();

            int index = profileComboBox.SelectedIndex;
            profileComboBox.Items.Remove(profile);

            if (index > 0)
                profileComboBox.SelectedIndex = index - 1;
            else
                profileComboBox.SelectedIndex = 0;
        }

        private void renameProfileButton_Click(object sender, EventArgs e)
        {
            updateProfile();

            if (selectedProfile == null)
                return;
            if (selectedProfile.ID == -1)
            {
                Logger.LogDebug("Default profile cannot be renamed");
                return;
            }

            using (Conf_NewProfile profileDlg = new Conf_NewProfile(selectedEmulator, selectedProfile))
            {
                if (profileDlg.ShowDialog() == DialogResult.OK)
                {
                    profileDlg.EmulatorProfile.Save();
                    int index = profileComboBox.SelectedIndex;
                    profileComboBox.Items.Remove(selectedProfile);
                    profileComboBox.Items.Insert(index, profileDlg.EmulatorProfile);
                    profileComboBox.SelectedIndex = index;
                }
            }
        }

        private void emuPathBrowseButton_Click(object sender, EventArgs e)
        {            
            string filter = "Executables (*.bat, *.exe) | *.bat;*.exe";

            string initialDirectory;
            int index = emuPathTextBox.Text.LastIndexOf("\\");

            if (index > -1)
                initialDirectory = emuPathTextBox.Text.Remove(index);
            else
                initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);

            using (OpenFileDialog dlg = Conf_GlobalSettings.OpenFileDialog("Select path to emulator", filter, initialDirectory))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                    emuPathTextBox.Text = dlg.FileName;
            }
        }

        void emuPathTextBox_TextChanged(object sender, EventArgs e)
        {
            if (selectedEmulator == null || selectedEmulator.PathToEmulator == emuPathTextBox.Text)
                return;

            string filters;
            EmulatorProfile autoSettings = EmuSettingsAutoFill.Instance.CheckForSettings(emuPathTextBox.Text, out filters);

            if (Options.Instance.GetBoolOption("autoconfemu"))
                updateFilterBox(filters);

            if (autoSettings == null)
                return;

            if (MessageBox.Show(string.Format("Would you like to use the recommended settings for {0}?", autoSettings.Title), "Use recommended settings?", MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                argumentsTextBox.Text = autoSettings.Arguments;
                useQuotesCheckBox.Checked = autoSettings.UseQuotes != false; //default to true if null
                suspendMPCheckBox.Checked = autoSettings.SuspendMP == true;
                if (autoSettings.WorkingDirectory == EmuSettingsAutoFill.USE_EMULATOR_DIRECTORY)
                {
                    System.IO.FileInfo file = new System.IO.FileInfo(emuPathTextBox.Text);
                    if (file.Exists)
                        workingDirTextBox.Text = file.Directory.FullName;
                }
                else
                    workingDirTextBox.Text = autoSettings.WorkingDirectory;

                mountImagesCheckBox.Checked = autoSettings.MountImages;
                escExitCheckBox.Checked = autoSettings.EscapeToExit;
            }
        }

        private void updateFilterBox(string filters)
        {
            if (string.IsNullOrEmpty(filters) || selectedEmulator == null)
                return;

            if (filterTextBox.Text == "")
            {
                filterTextBox.Text = filters;
                return;
            }
            
            List<string> currentFilters = new List<string>();
            currentFilters.AddRange(filterTextBox.Text.ToLower().Split(';'));
            int filterCount = currentFilters.Count;
            
            string[] newFilters = filters.ToLower().Split(';');

            for (int x = 0; x < newFilters.Length; x++)
            {
                if (!currentFilters.Contains(newFilters[x]))
                    currentFilters.Add(newFilters[x]);
            }

            if (currentFilters.Count == filterCount)
                return; //no new filters were added

            string newFilterString = "";
            for (int x = 0; x < currentFilters.Count; x++)
            {
                if (x != 0)
                    newFilterString += ";";
                newFilterString += currentFilters[x];
            }

            filterTextBox.Text = newFilterString;
        }

        Emulator newEmu = null;
        private void newEmuButton_Click(object sender, EventArgs e)
        {
            profGroupBox.Enabled = true;

            newEmuButton.Enabled = false;
            delEmuButton.Enabled = false;
            upButton.Enabled = false;
            downButton.Enabled = false;

            updateEmulator();
            updateProfile();
            
            clearForm();

            emulatorListView.Enabled = false;
            saveButton.Visible = true;
            cancelButton.Visible = true;

            newEmu = new Emulator();
            selectedEmulator = newEmu;
            selectedProfile = null;

            removeEventHandlers();

            emuPathTextBox.TextChanged += new EventHandler(emuPathTextBox_TextChanged); //allow path changed event to fire so auto-settings can be checked

            txt_Title.Text = "New Emulator";

            emuThumbs = new ThumbGroup(newEmu);
            pnlLogo.ThumbGroup = emuThumbs;
            pnlFanart.ThumbGroup = emuThumbs;

            profileComboBox.Items.Clear();
            profileComboBox.Items.Add(new EmulatorProfile(newEmu, false));
            profileComboBox.SelectedIndex = 0;
            profileComboBox.Enabled = false;
            addProfileButton.Enabled = false;

        }

        private void saveButton_Click(object sender, EventArgs e)
        {
            newEmu.Title = txt_Title.Text;

            newEmu.Company = txt_company.Text;
            newEmu.Description = txt_description.Text;
            newEmu.Grade = (int)gradeUpDown.Value;

            int year;
            if (!int.TryParse(txt_yearmade.Text, out year))
                year = 0;
            newEmu.Yearmade = year;

            newEmu.PathToRoms = romDirTextBox.Text;
            newEmu.Filter = filterTextBox.Text;
            newEmu.PathToEmulator = emuPathTextBox.Text;
            newEmu.Arguments = argumentsTextBox.Text;
            newEmu.WorkingFolder = workingDirTextBox.Text;
            newEmu.UseQuotes = useQuotesCheckBox.Checked;
            newEmu.SuspendRendering = suspendMPCheckBox.Checked;
            newEmu.EnableGoodmerge = enableGoodCheckBox.Checked;
            newEmu.GoodmergePref1 = good1ComboBox.Text;
            newEmu.GoodmergePref2 = good2ComboBox.Text;
            newEmu.GoodmergePref3 = good3ComboBox.Text;

            newEmu.MountImages = mountImagesCheckBox.Checked;

            newEmu.Position = emulatorListView.Items.Count;

            newEmu.Save();

            if (emuThumbs != null)
                emuThumbs.SaveAllThumbs();

            ListViewItem item = new ListViewItem(newEmu.Title) { Tag = newEmu };
            emulatorListView.Items.Add(item);
            selectedListItem = item;

            //updateEmuPositions = true;

            cancelButton_Click(cancelButton, new EventArgs());

        }

        private void cancelButton_Click(object sender, EventArgs e)
        {
            emulatorListView.Enabled = true;
            saveButton.Visible = false;
            cancelButton.Visible = false;
            profileComboBox.Enabled = true;
            addProfileButton.Enabled = true;

            newEmuButton.Enabled = true;
            delEmuButton.Enabled = true;
            upButton.Enabled = true;
            downButton.Enabled = true;

            emuPathTextBox.TextChanged -= new EventHandler(emuPathTextBox_TextChanged);

            addEventHandlers();

            emulatorListView.SelectedItems.Clear();
            if (selectedListItem != null)
                selectedListItem.Selected = true;
            else if (emulatorListView.Items.Count > 0)
                emulatorListView.Items[0].Selected = true;
                
        }

        private void romDirButton_Click(object sender, EventArgs e)
        {
            string title = "Select directory containg Roms";
            string initialDir;
            if (System.IO.Directory.Exists(romDirTextBox.Text))
                initialDir = romDirTextBox.Text;
            else
                initialDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            using (FolderBrowserDialog dlg = Conf_GlobalSettings.OpenFolderDialog(title, initialDir))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                    romDirTextBox.Text = dlg.SelectedPath;
            }
        }

        private void workingDirBrowseButton_Click(object sender, EventArgs e)
        {
            string title = "Select working directory";
            string initialDir;
            if (System.IO.Directory.Exists(workingDirTextBox.Text))
                initialDir = workingDirTextBox.Text;
            else if (emuPathTextBox.Text != "" && emuPathTextBox.Text.LastIndexOf("\\") > -1)
                initialDir = emuPathTextBox.Text.Remove(emuPathTextBox.Text.LastIndexOf("\\"));
            else
                initialDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            FolderBrowserDialog dlg = Conf_GlobalSettings.OpenFolderDialog(title, initialDir);
            if (dlg.ShowDialog() == DialogResult.OK)
                workingDirTextBox.Text = dlg.SelectedPath;
        }

        private void delEmuButton_Click(object sender, EventArgs e)
        {
            if(selectedEmulator == null || selectedEmulator.UID < 0)
                return;
            
            if (MessageBox.Show(
                string.Format("Are you sure you want to remove {0} and\r\nall of it's associated games from the database?", selectedEmulator.Title), 
                "Delete Emulator?", 
                MessageBoxButtons.YesNo) 
                != DialogResult.Yes)
                return;

            saveSelectedEmulator = false;
            saveThumbs = false;
            saveProfile = false;

            Game[] games = DB.Instance.GetGames(selectedEmulator);
            selectedEmulator.Delete();

            Importer importer = Conf_GlobalSettings.Instance.Importer;
            Conf_ProgressDialog progressDlg = new Conf_ProgressDialog(games, new ProgressDialogDelegate(delegate(object item)
            {
                Game game = (Game)item;
                importer.Remove(game.GameID);
                game.Delete();
                return "removing " + game.Title;
            }
            ));

            progressDlg.ShowDialog();
            progressDlg.Dispose();

            if (selectedListItem != null)
            {
                int index = selectedListItem.Index;
                if (index > 0)
                    index--;
                emulatorListView.Items.Remove(selectedListItem);
                if (emulatorListView.Items.Count > index)
                {
                    emulatorListView.SelectedItems.Clear();
                    emulatorListView.Items[index].Selected = true;
                }
            }
        }

        private void upButton_Click(object sender, EventArgs e)
        {
            if (selectedListItem == null || selectedListItem.Index == 0 || selectedEmulator == null)
                return;

            int index = selectedListItem.Index;
            emulatorListView.Items.Remove(selectedListItem);
            emulatorListView.Items.Insert(index - 1, selectedListItem);
            
            updateButtons();
            updateEmuPositions = true;
        }

        private void downButton_Click(object sender, EventArgs e)
        {
            if (selectedListItem == null || selectedListItem.Index == emulatorListView.Items.Count - 1 || selectedEmulator == null)
                return;

            int index = selectedListItem.Index;
            emulatorListView.Items.Remove(selectedListItem);
            emulatorListView.Items.Insert(index + 1, selectedListItem);

            updateButtons();
            updateEmuPositions = true;
        }

        #region ToolTip

        void setupToolTip()
        {
            emuToolTip.SetToolTip(newEmuButton, "Create new Emulator");
            emuToolTip.SetToolTip(delEmuButton, "Delete selected Emulator");
            emuToolTip.SetToolTip(upButton, "Move up");
            emuToolTip.SetToolTip(downButton, "Move down");

            emuToolTip.SetToolTip(saveButton, "Save new Emulator");

            emuToolTip.SetToolTip(addProfileButton, "Create new Profile");
            emuToolTip.SetToolTip(renameProfileButton, "Rename Profile");
            emuToolTip.SetToolTip(delProfileButton, "Delete Profile");

            emuToolTip.SetToolTip(romDirTextBox, "The directory where the Games are located");
            emuToolTip.SetToolTip(filterTextBox,
                @"The file filters used to determine games to import, Seperate filters with';'
e.g. '*.n64;*.z64;*.v64;*.rom'"
                );
            emuToolTip.SetToolTip(emuPathTextBox, "(Required) The path to the emulator exe/bat");
            emuToolTip.SetToolTip(workingDirTextBox, "(Optional) The Working Directory of the exe/bat when launched");
            emuToolTip.SetToolTip(argumentsTextBox,
                @"(Optional) Additional arguments to pass to the exe/bat.
The Game path will be appended to the end or will replace
%ROM% if present"
                );
            emuToolTip.SetToolTip(mountImagesCheckBox,
                @"If enabled the Plugin will mount games that are disk images using MediaPortal's VirtualDrive.
The VirtualDrive must be configured and enabled in MediaPortal's Configuration."
                );

        }

        #endregion

        private void btnNewManual_Click(object sender, EventArgs e)
        {
            string filter = "PDF | *.pdf";

            string initialDirectory;
            if (txt_Manual.Text != "" && txt_Manual.Text.LastIndexOf("\\") > -1)
                initialDirectory = txt_Manual.Text.Remove(txt_Manual.Text.LastIndexOf("\\"));
            else
                initialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);

            using (OpenFileDialog dlg = Conf_GlobalSettings.OpenFileDialog("Select manual", filter, initialDirectory))
            {
                if (dlg.ShowDialog() == DialogResult.OK)
                    txt_Manual.Text = dlg.FileName;
            }
        }

        private void btnManual_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrEmpty(txt_Manual.Text))
                return;

            if (!txt_Manual.Text.ToLower().EndsWith(".pdf") || !System.IO.File.Exists(txt_Manual.Text))
                return;

            using (System.Diagnostics.Process proc = new System.Diagnostics.Process())
            {
                proc.StartInfo = new System.Diagnostics.ProcessStartInfo(txt_Manual.Text);
                proc.Start();
            }
        }

    }
}
